<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <div th:replace="~{fragments/header :: header(title='注册')}"></div>
</head>
<body>
<div class="container mt-5" style="max-width: 500px;">
    <div class="card shadow">
        <div class="card-body">
            <!-- 注册标题 -->
            <h3 class="card-title mb-4 text-center">用户注册</h3>

            <!-- 注册表单 -->
            <form th:action="@{/user/register}" method="post" id="registerForm">
                <!-- 用户名 -->
                <div class="mb-3">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-control" name="username"
                           placeholder="请输入用户名" required>
                </div>

                <!-- 密码 -->
                <div class="mb-3">
                    <label class="form-label">密码</label>
                    <input type="password" class="form-control" name="password"
                           id="password" placeholder="至少6位字符" minlength="6" required>
                </div>

                <!-- 确认密码 -->
                <div class="mb-3">
                    <label class="form-label">确认密码</label>
                    <input type="password" class="form-control" name="confirmPassword"
                           placeholder="请再次输入密码" required>
                    <div class="invalid-feedback">两次密码输入不一致</div>
                </div>

                <!--注册错误提示消息-->
                <span th:text="${msg}" style="color: red"></span>

                <!-- 提交按钮 -->
                <button type="submit" class="btn btn-primary w-100 mb-3">立即注册</button>

                <!-- 已有账号提示 -->
                <div class="text-center">
                    <span>已有账号？</span>
                    <a th:href="@{/login.html}" class="text-decoration-none">去登录</a>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 交互脚本 -->
<script th:src="@{/js/register.js}"></script>
<script>
    // 密码一致性检查
    function checkPasswordMatch() {
        const password = document.getElementById('password').value;
        const confirmPassword = document.querySelector('input[name="confirmPassword"]');
        if (password !== confirmPassword.value) {
            confirmPassword.setCustomValidity('密码不匹配');
            confirmPassword.classList.add('is-invalid');
        } else {
            confirmPassword.setCustomValidity('');
            confirmPassword.classList.remove('is-invalid');
        }
    }

    // 绑定事件
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelector('input[name="confirmPassword"]').addEventListener('input', checkPasswordMatch);
    });

    // 表单提交拦截
    document.getElementById('registerForm').addEventListener('submit', function(e) {
        if (!this.checkValidity()) {
            e.preventDefault();
            Swal.fire('错误', '请检查表单填写是否正确', 'error');
        }
    });
</script>
</body>
</html>